from xml.dom.minidom import parse
from xml.dom.ext import PrettyPrint
from StringIO import StringIO

doc = parse('test.xml')
root = doc.documentElement
text = {'welcome': 'Enter command. For the list of commands enter "help"',
        'header': 'FilmLib ver.: 0.1.3',
        'help': '***List of commands***\n' +
                'lalal'}

def toprettyxml_fixed (node, encoding='utf-8'):
    tmpStream = StringIO()
    PrettyPrint(node, stream=tmpStream, encoding=encoding)
    return tmpStream.getvalue()

def add():
  name = raw_input('Enter film name:\n')
  type = raw_input('Enter film type:\n')
  shots = raw_input('Enter number of shots:\n')
  #film
  root.appendChild(doc.createElement('film'))
  #number
  number = doc.getElementsByTagName('film')
  root.lastChild.appendChild(doc.createElement('number'))
  root.lastChild.lastChild.appendChild(doc.createTextNode(str(number.length)))
  #name
  root.lastChild.appendChild(doc.createElement('name'))
  root.lastChild.lastChild.appendChild(doc.createTextNode(name))
  #type
  root.lastChild.appendChild(doc.createElement('type'))
  root.lastChild.lastChild.appendChild(doc.createTextNode(type))
  #shots
  root.lastChild.appendChild(doc.createElement('shots'))
  root.lastChild.lastChild.appendChild(doc.createTextNode(shots))

  f = open('test.xml', 'w')
  f.write(toprettyxml_fixed(doc, encoding='utf-8'))
  print toprettyxml_fixed(doc, encoding='utf-8')
  f.close()
  print 'Added succesfully'

def remove():
  number = raw_input('Enter the number of the film to be removed:\n')
  for i in doc.getElementsByTagName('number'):
    if i.childNodes[0].nodeValue == str(number):
      print i.childNodes[0].parentNode.removeChild('number')